package com.gang.core.pluginMgr;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import com.google.inject.Guice;
import com.google.inject.Injector;


public class PluginManager {
	static {
		System.out.println(PluginManager.class.getName());
	}
	private Map<String, PluginClassLoader> pluginMap = new HashMap<String, PluginClassLoader>();
	private static String packageName = "com.gang.plugins.";

	public PluginManager() {
	}

	public void doSome(String pluginName) {
		try {
			Class<?> forName = Class.forName(packageName+pluginName+".PluginAdapter", true,
					getLoader(pluginName));
			Plugin plugin = (Plugin) forName.newInstance();
			Injector injector = Guice.createInjector(plugin);
			injector.injectMembers(plugin);
			plugin.doSome();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
	public void loadPlugin(String pluginName){
		this.pluginMap.remove(pluginName);
		PluginClassLoader loader=new PluginClassLoader();
		String pluginUrl="jar:file:/D:/module/"+pluginName+".jar!/";
		URL jarUrl=null;
		try {
			jarUrl=new URL(pluginUrl);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		loader.addURLFile(jarUrl);
		addLoader(pluginName, loader);
		System.out.println("加载"+pluginName+"成功");
	}
	public void unload(String pluginName){
		this.pluginMap.get(pluginName).unloadJar();
		this.pluginMap.remove(pluginName);
	}
	private void addLoader(String pluginName,PluginClassLoader loader){
		this.pluginMap.put(pluginName, loader);
	}
	

	private PluginClassLoader getLoader(String pluginName) {
		return this.pluginMap.get(pluginName);
	}
}
